<template>
  <el-row>
    <el-col :span="12">
      <div class="left" style="margin: 20px 0 10px 100px">
        <el-carousel height="400px" @change="change" motion-blur>
          <el-carousel-item v-for="(pic,index) in goods.picList" :key="index">
            <el-image class="leftImg" :src="`${SERVER_ADDR}/goods/pic/${pic.url}`" fit="cover"
                      style="height: 400px;width: 400px"/>
            <!-- 鼠标层罩 -->
            <div v-show="topShow" class="top" :style="topStyle"></div>
            <!-- 最顶层覆盖了整个原图空间的透明层罩 -->
            <div
                class="maskTop"
                @mouseenter="enterHandler"
                @mousemove="moveHandler"
                @mouseout="outHandler"
            ></div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <div class="right" v-show="rShow">
        <el-image
            :style="r_img"
            class="rightImg"
            :src="SERVER_ADDR+'/goods/pic/'+num"
            alt=""
        />
      </div>
    </el-col>
    <el-col :span="12" style="height: 450px">
      <div style="height: 450px;width: 400px;margin:20px auto">
        <div class="product-info">
          <h1>{{ goods.name }}</h1>
          <p>{{ goods.dscp }}</p>
          <div class="promo">
            <h2>日丰管，管管，管管管</h2>
          </div>
          <div class="price">
            <span>¥{{ goods.price }}</span>
            <span style="margin-left: 10px; text-decoration: line-through;color: rgb(128,128,128);font-size: 18px">¥{{
                goods.markPrice
              }}</span>
          </div>
          <div class="product-specs">
            <table>
              <tbody>
              <tr>
                <th>型号</th>
                <td>{{ goods.version }}</td>
              </tr>
              <tr>
                <th>颜色</th>
                <td>{{ goods.color }}</td>
              </tr>
              <tr>
                <th>库存</th>
                <td>{{ goods.count }}</td>
              </tr>
              </tbody>
            </table>
          </div>
          <div class="options">
            <ul>
              <li class="car" @click="insertCart">加入购物车
                <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 1024 1024">
                  <path fill="#ffffff"
                        d="M432 928a48 48 0 1 1 0-96a48 48 0 0 1 0 96m320 0a48 48 0 1 1 0-96a48 48 0 0 1 0 96M96 128a32 32 0 0 1 0-64h160a32 32 0 0 1 31.36 25.728L320.64 256H928a32 32 0 0 1 31.296 38.72l-96 448A32 32 0 0 1 832 768H384a32 32 0 0 1-31.36-25.728L229.76 128zm314.24 576h395.904l82.304-384H333.44z"/>
                </svg>
              </li>
              <li class="like" v-if="!collectInfo" @click="collect">收藏
                <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
                  <path fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round"
                        stroke-width="1.5"
                        d="M12 21c-1.341 0-2.114-.572-3.66-1.717C.222 13.275 1.018 6.153 4.537 3.994c2.682-1.645 5.023-.982 6.429.074c.576.433.864.65 1.034.65s.458-.217 1.034-.65c1.406-1.056 3.747-1.719 6.429-.074C21.18 5.048 22.25 7.286 21.949 10M14 17h8m-4-4v8"
                        color="#ffffff"/>
                </svg>
              </li>
              <li class="unlike" v-else @click="cancelCollect">取消收藏
                <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
                  <path fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round"
                        stroke-width="1.5"
                        d="M12 21c-1.341 0-2.114-.572-3.66-1.717C.222 13.275 1.018 6.153 4.537 3.994c2.682-1.645 5.023-.982 6.429.074c.576.433.864.65 1.034.65s.458-.217 1.034-.65c1.406-1.056 3.747-1.719 6.429-.074C21.18 5.048 22.25 7.286 21.949 10M14 17h8m-4-4v8"
                        color="#ffffff"/>
                </svg>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
  <el-row>
    <!--  商品详情/商品评价-->
    <el-tabs model-value="first" class="demo-tabs">
      <el-tab-pane label="商品详情" name="first" v-html="goods.detail"></el-tab-pane>
      <el-tab-pane label="商品评价" name="second">
        <div v-for="(comment,index) in commentList" :key="index">
          <div>
            <span v-if="comment.status===0">{{ comment.user.username }}</span>
            <span v-else>匿名用户</span>
            <span>
                <el-rate
                    v-model="comment.score"
                    disabled
                    show-score
                    text-color="#ff6800"
                    score-template="{value}分"
                /></span>
            <span style="margin-left: 20px"><el-link v-if="comment.userId===user" style="float: right;margin-top: 30px;"
                                                     @click="delComment(comment.id)">删除</el-link></span>
          </div>
          <div v-html="comment.content" style="margin-left: 23px"></div>
          <div style="font-size: 12px;color: rgb(128,128,128);margin-left: 23px">{{ comment.createTime }}</div>
          <div v-if="comment.commentList.length>0">
            <div v-for="(c,index) in comment.commentList" :key="index" style="margin: 10px 0 10px 20px">
              <div v-html="c.content"></div>
              <div style="font-size: 12px;color: rgb(128,128,128)">{{ c.createTime }}</div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-row>
</template>


<script setup>
import {useRoute} from "vue-router";
import {ref} from "vue";
import goodsApi from "@/api/goodsApi.js";
import collectApi from "@/api/collectApi.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {useTokenStore} from '@/stores/token.js';
import cartApi from "@/api/cartApi.js";
import commentApi from "@/api/commentApi.js";

// 商品评论
const commentList = ref({});

const tokenStore = useTokenStore(); // 使用store

// 服务器的地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const route = useRoute();
// 需要展示的商品
const goods = ref({});
// 商品收藏的状态
const collectInfo = ref(null);

// 鼠标事件相关数据
const topStyle = ref({transform: ""});
const r_img = ref({});
const topShow = ref(false);
const rShow = ref(false);
const num = ref()

// 跳转到生成订单的页面
function toCreateOrderPage() {
  // 获取已经选中的购物车id
  let goodsId = route.query.id;
  router.push({
    path: "/user/createOrder",
    query: {
      goodsId,
    },
  });
}

// 加入购物车
function insertCart() {
  cartApi.insert(goods.value.id)
      .then((resp) => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg);
          ElMessageBox.confirm(
              "你要去购物车里瞅一眼嘛？",
              "Point",
              {
                confirmButtonText: "这就去",
                cancelButtonText: "下次一定",
                type: "warning",
              }
          )
              .then(() => {
                router.push("/user/cart");
                ElMessage({
                  type: "success",
                  message: "您已到达购物车",
                });
              });
          getCollectInfo(); // 刷新收藏的状态
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

function selectById() {
  let id = route.query.id;
  goodsApi.selectById(id)
      .then((resp) => {
        goods.value = resp.data;
        // 判断用户是否已经登录
        if (tokenStore.tokenStr != null) {
          // 获取当前商品收藏的情况
          getCollectInfo();
        }
      });
}

function getCollectInfo() {
  collectApi.selectByGoodsIdAndUserId(goods.value.id)
      .then((resp) => {
        collectInfo.value = resp.data;
      });
}

// 收藏
function collect() {
  collectApi.insert(goods.value.id)
      .then((resp) => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg);
          getCollectInfo(); // 刷新收藏的状态
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

// 取消收藏
function cancelCollect() {
  collectApi.delete(collectInfo.value.id)
      .then((resp) => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg);
          getCollectInfo(); // 刷新收藏的状态
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

selectById();

function searchAllComment() {
  const condition = {
    goodsId: route.query.id,
    parentId: 0,
  };
  commentApi.selectByCondition(condition)
      .then((resp) => {
        commentList.value = resp.data;
      });
}

searchAllComment();

function delComment(id) {
  ElMessageBox.confirm(
      `确认删除该评论吗？`,
      "删除评论确认",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
  )
      .then(() => {
        commentApi.delete(id)
            .then((resp) => {
              if (resp.code === 10000) {
                ElMessage.success("删除评论成功");
                searchAllComment();
                window.location.reload();
              } else {
                ElMessage.error(resp.msg);
              }
            });
      })
      .catch(() => {
        ElMessage.info("取消删除评论");
      });
}

// 鼠标进入原图空间函数
const enterHandler = () => {
  // 层罩及放大空间的显示
  topShow.value = true;
  rShow.value = true;
};

function change(n1, n2) {
  // console.log(n2, n1)
  // console.log(goods.value.picList[n1].url)
  num.value = goods.value.picList[n1].url;
}

// 鼠标移动函数
const moveHandler = (event) => {
  // 鼠标的坐标位置
  let x = event.offsetX;
  let y = event.offsetY;
  // 层罩的左上角坐标位置，并对其进行限制：无法超出原图区域左上角
  let topX = x - 100 < 0 ? 0 : x - 100;
  let topY = y - 100 < 0 ? 0 : y - 100;
  // 对层罩位置再一次限制，保证层罩只能在原图区域空间内
  if (topX > 200) {
    topX = 200;
  }
  if (topY > 200) {
    topY = 200;
  }
  // 通过 transform 进行移动控制
  topStyle.value.transform = `translate(${topX}px,${topY}px)`;
  r_img.value.transform = `translate(-${2 * topX}px,-${2 * topY}px)`;
};

// 鼠标移出函数
const outHandler = () => {
  // 控制层罩与放大空间的隐藏
  topShow.value = false;
  rShow.value = false;
};
</script>

<style scoped>
el-carousel {
  border: 2px solid #AAA;
}

.product-info {
  margin-top: 10px;
}

.price {
  color: #ff4136;
  font-size: 24px;
}

.promo {
  margin: 20px 0;
}

.promo h2 {
  color: #34495e;
}

.options {
  margin-top: 10px;
}

table {
  margin: 25px 0;
  width: 100%;
  border-collapse: collapse;
}

th, td {
  text-align: left;
  padding: 8px;
  border: 1px solid black;
}

th {
  background-color: #f6f3f3;
}

.demo-tabs {
  --el-tag-bg-color: red
}

.options ul li {
  display: inline-block;
  padding: 10px 20px;
  background-color: rgba(255, 255, 255, 1);
  color: black;
  text-decoration: none;
  border: 1px solid black;
  font-size: 16px;
  width: 120px;
  text-align: center;
  margin: 5px;
}

.options ul li:hover {
  color: var(--theme-color);
  border: 1px solid var(--theme-color);
}

.options .car {
  background-color: #FF6700;
  width: 160px;
  color: white;
}

.options .car:hover {
  background-color: white;
  width: 160px;
  color: #FF6700;

  svg path {
    fill: #FF6700;
  }
}

.options .like {
  background-color: red;
  width: 120px;
  color: white;
}

.options .like:hover {
  background-color: white;
  width: 120px;
  color: red;

  svg path {
    stroke: #ff0000;
  }
}

.options .unlike {
  background-color: grey;
  width: 120px;
  color: white;
}

.options .unlike:hover {
  background-color: white;
  width: 120px;
  color: grey;

  svg path {
    stroke: grey;
  }
}

/* 放大的图片，通过定位将左上角定位到(0,0) */
.rightImg {
  display: inline-block;
  width: 800px;
  height: 800px;
  position: absolute;
  top: 0;
  left: 0;
}

/* 右边的区域图片放大空间 */
.right {
  margin-left: 700px;
  margin-top: 10px;
  width: 400px;
  height: 400px;
  border: 1px solid red;
  position: fixed;
  overflow: hidden;
}

/* 一个最高层层罩 */
.maskTop {
  width: 400px;
  height: 400px;
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
}

/* 层罩，通过定位将左上角定位到(0,0) */
.top {
  width: 200px;
  height: 200px;
  background-color: lightcoral;
  opacity: 0.4;
  position: absolute;
  top: 0;
  left: 0;
}

/* 原图的显示 */
.leftImg {
  width: 400px;
  height: 400px;
  display: inline-block;
}

/* 原图的容器 */
.left {
  width: 400px;
  height: 400px;
  border: 1px solid teal;
  float: left;
  position: relative;
}
</style>
